package mvc.model.inventory

import app.AppContext
import com.hontech.pizzav2.R
import event.motor.MotorCode
import event.motor.ScanStatusChangedEvent
import ext.log
import ext.toTimeStamp
import org.json.JSONObject

class ScanModel(val row: String, val col: String, val barCode: String, val result: String) {

    companion object {
        fun withScanEvent(env: ScanStatusChangedEvent): ScanModel {
            val arr = AppContext.resources.getStringArray(R.array.return_value)
            val row = env.row.toString()
            val col = env.col.toString()
            val barCode = if (env.state != MotorCode.OK) "No barcode" else env.barCode()
            val result = if (env.state in MotorCode.range) arr[env.state] else "error"
            return ScanModel(row, col, barCode, result)
        }
    }

    val productionDate: Long

    init {
        productionDate = if (isExist()) {
            try {
                barCode.toTimeStamp()
            } catch (e: Exception) {
                e.printStackTrace()
                -1.toLong()
            }
        } else {
            0.toLong()
        }

        log("${name()} - $barCode - $productionDate", "条码信息")
    }

    fun name() = "$col-$row"

    fun isExist(): Boolean {
        return barCode != "No barcode"
    }

    fun toJson(): JSONObject {
        val json = JSONObject()
        json.put("goodsType", name())
        json.put("barCode", barCode)
        json.put("productionDate", productionDate)
        return json
    }

}